﻿using System;
using System.Diagnostics;
using System.IO;

namespace AirXBMC
{
    public class MySettings
    {
        // saved data
        public int ServicePort;
        public string XbmcAddress;

        #region Constructor/Destructor and Singleton

        // Singleton instance
        public static MySettings Instance = LoadSettings();

        private MySettings() { }

        #endregion

        #region Defaults

        private void SetDefaultValues()
        {
            // create default values if loading xml file fails or file doesnt exist
            ServicePort = 7000;
            XbmcAddress = "http://localhost:8080";
        }

        #endregion

        #region Loading/Saving

        public void SaveSettings()
        {
            Debug.WriteLine(" >>> Saving configuration");
            XmlSerialization.SerializeObjectToXmlFile("configuration.xml", this);
        }

        private static MySettings LoadSettings()
        {
            try
            {
                Debug.WriteLine(" >>> Loading configuration");
                var data = XmlSerialization.DeserializeXmlFileToObject<MySettings>("configuration.xml");
                return data;
            }
            catch (Exception ex)
            {
                var defaults = new MySettings();
                defaults.SetDefaultValues();
                if (ex is FileNotFoundException)
                {
                    Debug.WriteLine(" >>> Configuration file not found. Using defaults.");
                    defaults.SaveSettings();
                }
                else
                {
                    Debug.WriteLine(" >>> Configuration file found but failed to load:");
                    Debug.WriteLine(string.Format("Message: {0}", ex.Message));
                }
                return defaults;
            }
        }

        #endregion
    }
}
